package com.yuwj.chinaa.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yuwj.chinaa.R;
import com.yuwj.chinaa.base.BaseActivity;
import com.yuwj.chinaa.entity.EntityAssetsBag;
import com.yuwj.chinaa.entity.EntityBurseCoinNumber;
import com.yuwj.chinaa.entity.EntityReceivingAddress;
import com.yuwj.chinaa.presenter.IPresenter;
import com.yuwj.chinaa.presenter.presenterImpl.PresenterImpl;
import com.yuwj.chinaa.util.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

//资产包详情界面
public class AssetsBagDetailActivity extends BaseActivity {
    //    @BindView(R.id.tv_title)
//    TextView tvTitle;
//    @BindView(R.id.tv_price)
//    TextView tvAssetsPrice;
//    @BindView(R.id.et_amount)
//    EditText etAssetsAmount;
//    @BindView(R.id.tv_buy_way)
//    TextView tvBuyWay;
//    @BindView(R.id.tv_chinaa_cur_price)
//    TextView tvChinaACurrentPrice;
//    @BindView(R.id.chinaa_user_amount)
//    TextView tvChinaAUseAmount;
    AlertDialog dialogWithPayPasswordInput;//付款密码输入框
    AlertDialog dialogWithPayTip;//付款购买后提示,包括购买成功，购买失败

    IPresenter presenter;
    EntityAssetsBag entityAssetsBag;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.et_amount)
    EditText etAmount;
    @BindView(R.id.tv_buy_way)
    TextView tvBuyWay;
    @BindView(R.id.tv_chinaa_cur_price)
    TextView tvChinaaCurPrice;
    @BindView(R.id.tv_chinaa_use_amount)
    TextView tvChinaaUseAmount;
    private EntityBurseCoinNumber entityBurseCoinNumber;
    private boolean hasReceiveAddress;

    @Override
    public int setCustomContentViewResourceId() {
        return R.layout.activity_assets_bag_detail;
    }

    public static Intent createIntent(Context context, EntityAssetsBag entityAssetsBag) {
        Intent intent = new Intent(context, AssetsBagDetailActivity.class);
        intent.putExtra("entityAssetsBag", entityAssetsBag);
        return intent;
    }

    @Override
    public void initParam() {
        presenter = new PresenterImpl(this);
        entityAssetsBag = (EntityAssetsBag) getIntent().getSerializableExtra("entityAssetsBag");
    }

    @Override
    public void initView() {

        tvTitle.setText(entityAssetsBag.getAssetName());
        if (entityAssetsBag.getAssetType() == 20030002){//普通用户
            tvPrice.setText(entityAssetsBag.getAssetPriceDJ() + "元");
        }else {
            tvPrice.setText(entityAssetsBag.getAssetPriceDJ() + " china-A");
        }
        tvChinaaCurPrice.setText(entityAssetsBag.getPriceRMB() + "元" + "  china-A");
        int count = 0;
        try {
            count = Integer.valueOf(etAmount.getText().toString());
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        tvChinaaUseAmount.setText(entityAssetsBag.getAssetCoinNumber()+ "个  china-A");
        etAmount.setSelection(etAmount.getText().toString().trim().length());
        etAmount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                int count = 0;
                try {
                    count = Integer.valueOf(etAmount.getText().toString());
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
                tvChinaaUseAmount.setText(entityAssetsBag.getAssetCoinNumber()+ "个  china-A");
            }
        });
    }

    @Override
    public void initOperator() {
        JSONObject param = new JSONObject();
        try {
            param.put("assetId", entityAssetsBag.getID() + "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        presenter.getAssetsDetailById(param.toString());
        presenter.getUserBurseCoinNumberList("");
        presenter.getReceiveAddressList("");


    }

    @OnClick({R.id.iv_back, R.id.tv_confirm_buy})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                onBackPressed();
                break;
            case R.id.tv_confirm_buy:
                if (TextUtils.isEmpty(etAmount.getText().toString())) {
                    ToastUtil.getInstance().shortLength(context, "请输入购买数量");
                    return;
                }
               int count = Integer.valueOf(etAmount.getText().toString());
//               double useAmount= count * entityAssetsBag.getAssetCoinNumber();
//               //当前可用余额小于使用数量
//               if (entityBurseCoinNumber.getAvailableBurseCoinNumber()< useAmount){
//                   ToastUtil.getInstance().shortLength(context, "可用china-A数量不足");
//                   return;
//               }
               if(count > entityAssetsBag.getBuyMaxAtlasCount()){
                   ToastUtil.getInstance().shortLength(context, "图册数量超出限制");
                   return;
               }

                if (TextUtils.isEmpty(entityUser.getWithdrawPwd())) {
                    android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(context);
                    final android.support.v7.app.AlertDialog dialog = builder.create();
                    dialog.setTitle("提示");
                    dialog.setMessage("您还未设置支付密码,请先前往设置");
                    android.support.v7.app.AlertDialog.OnClickListener alertDialogOnclickListener = new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            switch (i) {
                                case android.support.v7.app.AlertDialog.BUTTON_POSITIVE:
                                    startActivity(AccountUpdatePaymentPasswordActivity.createIntent(context));
                                    dialog.dismiss();
                                    break;
                                case android.support.v7.app.AlertDialog.BUTTON_NEGATIVE:
                                    dialog.dismiss();
                                    break;
                            }
                        }
                    };
                    dialog.setButton(android.support.v7.app.AlertDialog.BUTTON_POSITIVE, "确定", alertDialogOnclickListener);
                    dialog.setButton(android.support.v7.app.AlertDialog.BUTTON_NEGATIVE, "取消", alertDialogOnclickListener);
                    dialog.show();
                    return;
                }

                if (!hasReceiveAddress){
                    android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(context);
                    final android.support.v7.app.AlertDialog dialog = builder.create();
                    dialog.setTitle("提示");
                    dialog.setMessage("您还未设置收货地址,请先前往设置");
                    android.support.v7.app.AlertDialog.OnClickListener alertDialogOnclickListener = new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            switch (i) {
                                case android.support.v7.app.AlertDialog.BUTTON_POSITIVE:
                                    startActivity(ReceiveAddressUpdateActivity.createIntent(context, null, 0));//新增地址

                                    dialog.dismiss();
                                    break;
                                case android.support.v7.app.AlertDialog.BUTTON_NEGATIVE:
                                    dialog.dismiss();
                                    break;
                            }
                        }
                    };
                    dialog.setButton(android.support.v7.app.AlertDialog.BUTTON_POSITIVE, "确定", alertDialogOnclickListener);
                    dialog.setButton(android.support.v7.app.AlertDialog.BUTTON_NEGATIVE, "取消", alertDialogOnclickListener);
                    dialog.show();
                    return;
                }


                showPayPasswordInputDialog();
                break;
        }
    }

    //展示支付密码对话框
    public void showPayPasswordInputDialog() {
        if (dialogWithPayPasswordInput == null) {
            AlertDialog.Builder builderWithPay = new AlertDialog.Builder(context);
            LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(R.layout.content_input_pay_password, null);
            final EditText etPayPassword = (EditText) layout.findViewById(R.id.et_pay_password);
            LinearLayout llDismiss = (LinearLayout) layout.findViewById(R.id.ll_dismiss);
            TextView tvBuy = (TextView) layout.findViewById(R.id.tv_buy);
            View.OnClickListener onClickListener = new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    switch (view.getId()) {
                        case R.id.ll_dismiss:
                            dialogWithPayPasswordInput.dismiss();
                            break;
                        case R.id.tv_buy:
                            String passwrod = etPayPassword.getText().toString();
                            if (TextUtils.isEmpty(passwrod)) {
                                ToastUtil.getInstance().shortLength(context, "请输入支付密码");
                                return;
                            }
                            JSONObject param = new JSONObject();
                            try {
                                param.put("assetId", entityAssetsBag.getID() + "");
                                param.put("atlasNumber", etAmount.getText().toString() + "");
                                param.put("tradePwd", etPayPassword.getText().toString() + "");


                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            presenter.BuyAssets(param.toString());

                            etPayPassword.setText("");//发送请求后,清空输入的密码
                            dialogWithPayPasswordInput.dismiss();
                            break;
                    }
                }
            };
            llDismiss.setOnClickListener(onClickListener);
            tvBuy.setOnClickListener(onClickListener);
            dialogWithPayPasswordInput = builderWithPay.setView(layout).create();
        }
        dialogWithPayPasswordInput.show();
    }


    //展示支付结果对话框
    public void showPayTipDialog(String title, String msg) {
        if (dialogWithPayTip == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle(title);
            builder.setMessage(msg);
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                    finish();
                }
            });
            dialogWithPayTip = builder.create();
            dialogWithPayTip.setCancelable(false);
            dialogWithPayTip.setCanceledOnTouchOutside(false);
        }
        dialogWithPayTip.show();

    }


    @Override
    public void onGetAssetsDetailSuccess(EntityAssetsBag entityAssetsBag) {
        super.onGetAssetsDetailSuccess(entityAssetsBag);
        this.entityAssetsBag = entityAssetsBag;
        initView();
    }

    @Override
    public void onGetAssetsDetailFail(Exception e) {
        super.onGetAssetsDetailFail(e);
        ToastUtil.getInstance().shortLength(context, e.getMessage());
    }

    @Override
    public void onBuyAssetsSuccess() {
        super.onBuyAssetsSuccess();
        if (entityAssetsBag.getAssetName().equals("China-A业务合伙人") || entityAssetsBag.getAssetName().equals("China-A事业合伙人")
                || entityAssetsBag.getAssetName().equals("China-A董事合伙人")) {
            showPayTipDialog("尊敬的用户恭喜您参与china-A的合伙人计划", "购买成功！");

        } else {
            showPayTipDialog("", "购买成功！");
        }
    }

    @Override
    public void onBuyAssetsFail(Exception e) {
        super.onBuyAssetsFail(e);
        showPayTipDialog("", e.getMessage());

    }

    @Override
    public void onGetUserBurseCoinNumberListSuccess(EntityBurseCoinNumber entityBurseCoinNumber) {
        super.onGetUserBurseCoinNumberListSuccess(entityBurseCoinNumber);
        this.entityBurseCoinNumber = entityBurseCoinNumber;
    }

    @Override
    public void onGetUserBurseCoinNumberListFail(Exception e) {
        super.onGetUserBurseCoinNumberListFail(e);
        ToastUtil.getInstance().shortLength(context, "" + e.getMessage());
    }


    @Override
    public void onGetReceiveAddressListSuccess(List<EntityReceivingAddress> list) {
        super.onGetReceiveAddressListSuccess(list);
        if (list != null && list.size() > 0) {
           hasReceiveAddress=true;
        } else {
           hasReceiveAddress=false;
        }
    }

    @Override
    public void onGetReceiveAddressListFail(Exception e) {
        super.onGetReceiveAddressListFail(e);
        hasReceiveAddress=false;
        ToastUtil.getInstance().shortLength(context, e.getMessage());
    }
}
